<?php

include '../../control.php';

/**
 * Class mygit
 * @property repoModel $repo
 * @property dao $dao
 */
class mygit extends git
{
    /**
     * Sync from the syncer by api. // FromGitlab
     *
     * @access public
     * @return void
     */
    public function apiSync()
    {
        // 从 Gitlab webhook 服务推送过来的JSON格式的数据数据
        $data = json_decode(file_get_contents('php://input'));
        if (!$data || !$data->commits) {
            echo 'Fail';
            return;
        }

        if (!$_SERVER['HTTP_X_GITLAB_TOKEN'] || ($_SERVER['HTTP_X_GITLAB_TOKEN'] != $this->config->git->gitlabToken)) {
            echo 'Fail';
            return;
        }

//        if ($data->object_kind != 'push') {
//            return;
//        }

        $repoRoot = ''; // todo $this->post->repoRoot;

        $parsedLogs = array();

        foreach($data->commits as $log)
        {
            $parsedLog = new stdClass();

            $account = '';
            $user = null;
            // 先按源代码账号进行匹配
            if ($log->author->username) {
                $user = $this->dao->select('*')->from(TABLE_USER)->where("commiter")->eq($log->author->username)->fetch();
            }
            // 再按账号匹配
            if (!$user && $log->author->username) {
                $user = $this->dao->select('*')->from(TABLE_USER)->where("account")->eq($log->author->username)->fetch();
            }
            // 最后再根据邮箱找账号
            if (!$user && $log->author->email) {
                $user = $this->dao->select('*')->from(TABLE_USER)->where("email")->eq($log->author->email)->fetch();
            }
            if ($user) {
                $account = $user->account;
            }

            $parsedLog->author    = $account;
            $parsedLog->revision  = $log->id;
            $parsedLog->msg       = trim($log->message);
            $parsedLog->date      = date('Y-m-d H:i:s', strtotime($log->timestamp));

            $parsedLog->files     = [];
            if ($log->added) {
                $parsedLog->files['A'] = $log->added;
            }
            if ($log->modified) {
                $parsedLog->files['M'] = $log->modified;
            }

            if ($log->removed) {
                $parsedLog->files['D'] = $log->removed;
            }
            $parsedLogs[] = $parsedLog;
        }

        $this->loadModel('repo');

        foreach($parsedLogs as $log) {
            $objects = $this->repo->parseComment($log->msg);

            $this->repo->saveAction2PMS($objects, $log, $repoRoot, 'utf-8', 'git');
        }
        echo 'Success';
        exit;

    }
}